package com.cashmama.market.api.integration.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.domain.integration.AdvanceAiIntegrationService;
import com.cashmama.market.api.domain.utils.Amazon2OssUtils;
import com.cashmama.market.api.domain.vo.RequestLocalInfo;
import com.cashmama.market.api.domain.vo.aadhaar.*;
import com.cashmama.market.api.domain.vo.user.UserBriefDTO;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.consts.RedisKeyConsts;
import com.cashmama.market.api.infras.consts.TimeConsts;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.cashmama.market.api.infras.utils.DateUtil;
import com.cashmama.market.api.infras.utils.HttpUtil;
import com.cashmama.market.api.infras.utils.StringUtils;
import com.fqgj.base.services.amazon.AmazonS3Service;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserBehaviorService;
import com.fqgj.xjd.user.client.enums.UserEventTrackEnum;
import com.fqgj.xjd.user.client.enums.UserOcrTypeEnum;
import com.fqgj.xjd.user.client.request.ThirdCallHistoryRequest;
import com.fqgj.xjd.user.client.request.UserBehaviorEvent2Request;
import com.google.common.base.Joiner;
import com.qianli.cashmama.trade.common.utils.signature.Base64ConvertUtil;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2019-12-20 16:36
 **/
@Service
public class AdvanceAiIntegrationServiceImpl implements AdvanceAiIntegrationService {

    private final static Logger LOGGER = LoggerFactory.getLogger(AdvanceAiIntegrationServiceImpl.class);
    private static final String ACCUAUTH_OCR_URL = "https://cloudapi.accuauth.com/ocr/indian_card";
    private static final String ANTI_HACK_URL = "https://cloudapi.accuauth.com/face/liveness_anti_hack";
    private static final String OK = "OK";
    private static final String CHECK_URL = "https://in-api.advance.ai/in/openapi/verification/v1/identity-getList";

    private static final String CHECK_RESULT_URL = "https://in-api.advance.ai/in/openapi/verification/v1/identity-getList-result";

    private static final String ADVANCE_OCR_URL = "https://in-api.advance.ai/in/openapi/face-identity/v2/ocr";
    private static final String ADVANCE_OCR_URL_New = "https://in-api.advance.ai/in/openapi/face-identity/v1/id-card-ocr";

    private static final String ADVANCE_LIVENESS_DETECTION_LICENSE = "https://in-api.advance.ai/in/openapi/face-identity/v1/auth-license";
    private static final String ADVANCE_LIVENESS_DETECTION = "https://in-api.advance.ai/in/openapi/face-identity/v1/liveness-detection";

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private OSSService ossService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    DeepFinchHttpManager deepFinchHttpManager;

    @Autowired
    private UserBehaviorService userBehaviorService;

    @Autowired
    private AmazonS3Service amazonS3Service;

    @Override
    public void aadhaarCheck(String userCode, String aadhaarNo, UserBriefDTO userBriefDTO) {

//        if (userAdvanceIntegrationService.advanceAadhaarActionComplete(userCode)) {
//            LOGGER.info("advanceAi已认证,略过1,userCode:{}", userCode);
//            throw new ApiErrorException("Verification succeeded, please refresh");
//        }
//        UserBriefDTO userBriefDTO = userIntegrationService.getUserBriefInfoByUserCode(userCode);
        if (!apolloConfigUtil.isServerTest()) {
            String transactionId = this.identityCheck(aadhaarNo, userBriefDTO.getName(), userBriefDTO.getMobile(), userBriefDTO.getEmail());
            redisClient.set(RedisKeyConsts.ADVANCEAI_TRANSACTIONID_KEY, transactionId, TimeConsts.TEN_MINUTES, userCode, aadhaarNo);
        }
    }

    /**
     * 身份验证
     *
     * @param aadhaarNo
     * @param name
     * @param phoneNumber
     * @param email
     */
    @Override
    public String identityCheck(String aadhaarNo, String name, String phoneNumber, String email) {
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("X-ADVAI-KEY", apolloConfigUtil.getAadhaarAdvanceAiAccessKey());

        JSONObject request = new JSONObject();
        request.put("aadhaarNumber", aadhaarNo);//会真的发短信 所以测试环境可以用Bhushan的
        request.put("name", name);
        request.put("phoneNumber", phoneNumber);
        request.put("email", email);

        String responseStr = HttpUtil.postPageBodyByHttps(CHECK_URL, header, request.toJSONString());
        LOGGER.info("调用AdvanceAi校验接口,header:{},request:{},response:{}", JSON.toJSONString(header), request.toJSONString(), responseStr);
        if (!this.isJson(responseStr)) {
            LOGGER.error("调用AdvanceAi校验接口失败,userCode:{},request:{},response:{}", JSON.toJSONString(header), request.toJSONString(), responseStr);
            throw new ApplicationException("Failed!");
        }
        JSONObject response = JSON.parseObject(responseStr);

        String code = response.getString("code");
        String message = response.getString("message");
        String transactionId = response.getString("transactionId");
        String pricingStrategy = response.getString("pricingStrategy");
        String extra = response.getString("extra");
        if (!"SUCCESS".equals(code)) {
            LOGGER.info("aadhaar认证失败,aadhaarNo:{},message:{}", aadhaarNo, message);
            throw new ApplicationException("Failed: " + message);
        }
        //发起下一步 Advance会给用户发送短信
        return transactionId;
    }

    /**
     * 身份验证结果
     *
     * @param transactionId
     * @param OPT
     */
    @Override
    public String identityCheckResult(String userCode, String transactionId, String OPT) {
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("X-ADVAI-KEY", apolloConfigUtil.getAadhaarAdvanceAiAccessKey());

        JSONObject request = new JSONObject();
        request.put("transactionId", transactionId);
        request.put("otpCode", OPT);

        String responseStr = HttpUtil.postPageBodyByHttps(CHECK_RESULT_URL, header, request.toJSONString());
        LOGGER.info("调用AdvanceAi校验接口,userCode:{},header:{},request:{},response:{}", userCode, JSON.toJSONString(header), request.toJSONString(), responseStr);
        if (!this.isJson(responseStr)) {
            LOGGER.error("调用AdvanceAi校验接口失败,userCode:{},request:{},response:{}", JSON.toJSONString(header), request.toJSONString(), responseStr);
            throw new ApplicationException("Failed!");
        }
        JSONObject response = JSON.parseObject(responseStr);

        String code = response.getString("code");
        String message = response.getString("message");
        if (!"SUCCESS".equals(code)) {
            throw new ApplicationException("Failed");
        }
        JSONObject data = response.getJSONObject("data");
        if (data == null || data.size() == 0) {
            throw new ApplicationException("Failed");
        }
        String photoBase64 = data.getString("photo");
        if (StringUtils.isNotEmpty(photoBase64)) {
            String date = DateUtil.getDate(new Date());
            InputStream inputStream = Base64ConvertUtil.base64ToPdf(photoBase64);
            String fileStr = Joiner.on("_").join(userCode, date, System.currentTimeMillis(), "advance.png");
            String ossFilePath = "advance/" + date + "/" + fileStr;
            String fileUrl = "";
            try {
                ossService.uploadFile(apolloConfigUtil.getBucketName(), inputStream, inputStream.available(), ossFilePath);
                fileUrl = apolloConfigUtil.getQsyqBaseUrl() + ossFilePath;
            } catch (Exception e) {
                LOGGER.error("上传图片失败,transactionId:{},photoBase64:{}", transactionId, photoBase64, e);
            } finally {
                try {
                    inputStream.close();
                } catch (Exception ex) {
                }
            }
            data.put("photo", fileUrl);
        }
        return data.toJSONString();
    }

    @Override
    public Response<String> ocr(String imgUrl) {
        Map<String, String> parameters = new HashMap<>(1);
        parameters.put("url", imgUrl);
        Map<String, String> headers = new HashMap<>(2);
        headers.put("X_DF_API_ID", apolloConfigUtil.getDeepFinchAppId());
        headers.put("X_DF_API_SECRET", apolloConfigUtil.getDeepFinchAppSecret());
        String jsonStr = com.fqgj.common.utils.HttpUtil.postPage(ACCUAUTH_OCR_URL, parameters, headers);
        LOGGER.info("====AccuauthOcr接口调用======:imgUrl:{},response:{}", imgUrl, jsonStr);
        if (com.fqgj.common.utils.StringUtils.isEmpty(jsonStr)) {
            return Response.error("Internal Server Error");
        }
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String status = jsonObject.getString("status");
        if (Objects.equals(OK, status)) {
            LOGGER.info("====AccuauthOcr接口调用成功======:imgUrl:{},response:{}", imgUrl, jsonStr);
            return Response.ok().putData(JSON.toJSONString(jsonObject));
        } else {
            return Response.error(jsonObject.getString("reason"));
        }
    }

    /**
     * 新ocr识别
     *
     * @param frontImgUrl
     * @param backImgUrl
     * @return
     */
    @Override
    public Response<OcrResponseVO> ocrAadhaar(String frontImgUrl, String backImgUrl) {
        LOGGER.info("== 进入advance ocr ==,frontImgUrl:{},type:{}", frontImgUrl, "aadhaar");
        if (frontImgUrl == null) {
            LOGGER.error("== 进入advance ocr ocr url is empty ==");
            return Response.error("ocr url is empty");
        }

        String errorMsg = "Please take photos at a slightly longer distance for clear %s photo";
        String notRealPhotoMsg = "Please upload your real %s photo.";
        errorMsg = String.format(errorMsg, "aadhaar");
        notRealPhotoMsg = String.format(notRealPhotoMsg, "aadhaar");
//        if ("AADHAAR".equalsIgnoreCase(paramsCardType)) {
//        } else {
//            errorMsg = String.format(errorMsg, "pancard");
//            notRealPhotoMsg = String.format(notRealPhotoMsg, "pancard");
//        }

        try {
            String front = downloadImg(Amazon2OssUtils.convertOssUrl(frontImgUrl));

            if (front == null) {
                LOGGER.error("== 进入advance ocr download front error ==,frontImgUrl:{}",frontImgUrl);
                return Response.error("download error");
            }

            File frontFile = new File(front);
            if (!frontFile.exists()) {
                LOGGER.error("== 进入advance ocr file not exist local ==");
                return Response.error("file not exist local");
            }
            String back = downloadImg(Amazon2OssUtils.convertOssUrl(backImgUrl));

            if (back == null) {
                LOGGER.error("== 进入advance ocr download back error ==");
                return Response.error("download error");
            }

            File backFile = new File(back);
            if (!backFile.exists()) {
                LOGGER.error("== 进入advance ocr file not exist local ==");
                return Response.error("file not exist local");
            }

            String frontOcrRes = ocrNew(frontFile, UserOcrTypeEnum.AADHAAR_FRONT);
            String backOcrRes = ocrNew(backFile, UserOcrTypeEnum.AADHAAR_BACK);
            LOGGER.info("== ocr返回内容 ==， frontOcrRes:{},backOcrRes:{}", frontOcrRes, backOcrRes);


            JSONObject jsonObject = JSON.parseObject(frontOcrRes);
            String code = jsonObject.getString("code");
            if (StringUtils.isNotEmpty(code) && !code.equalsIgnoreCase("SUCCESS")) {
                return Response.error(notRealPhotoMsg);
            }

            JSONObject dataObjectFront = jsonObject.getJSONObject("data");
            JSONObject resultObjectFront = dataObjectFront.getJSONObject("values");

            JSONObject jsonObject2 = JSON.parseObject(backOcrRes);
            String code2 = jsonObject2.getString("code");
            if (StringUtils.isNotEmpty(code2) && !code2.equalsIgnoreCase("SUCCESS")) {
                return Response.error(notRealPhotoMsg);
            }

            JSONObject dataObjectBack = jsonObject2.getJSONObject("data");
            JSONObject resultObjectBack = dataObjectBack.getJSONObject("values");

            OcrCardInfoVO ocrCardInfoVo = new OcrCardInfoVO()
                    .setCard_no(resultObjectFront.getString("idNumber").replace(" ", ""))
                    .setDate_type("DOB")
                    .setName(resultObjectFront.getString("name"))
                    .setDate_info(resultObjectFront.getString("birthday"))
                    .setGender(resultObjectFront.getString("gender"))
                    .setState(resultObjectBack.getString("state"))
                    .setPin(resultObjectBack.getString("pin"))
                    .setCity(resultObjectBack.getString("district"))
                    .setCity(resultObjectBack.getString("subdistrict"))
                    .setAddress_line_one(resultObjectBack.getString("other"))
                    .setAddress(resultObjectBack.getString("addressAll"));
//                    .setFather_name(resultObject.getString("fatherName"));
            OcrCardResultVO ocrCardResultVoFront = new OcrCardResultVO()
                    .setCard_info(ocrCardInfoVo);

            OcrResponseVO ocrResponseVoFront = new OcrResponseVO()
                    .setRequest_id(jsonObject.getString("transactionId") + "|" + jsonObject2.getString("transactionId"))
                    .setStatus(jsonObject.getString("message"))
                    .setResults(Arrays.asList(ocrCardResultVoFront));

            return Response.ok().putData(ocrResponseVoFront);


        } catch (Exception e) {
            LOGGER.error("== 调用advance ai 异常2 ==", e);
        }

        return Response.error(errorMsg);
    }

    @Override
    public Response<OcrResponseVO> ocrPan(String frontImgUrl) {
        LOGGER.info("== 进入advance ocr ==,frontImgUrl:{},type:{}", frontImgUrl, "pan");
        if (frontImgUrl == null) {
            LOGGER.error("== 进入advance ocr ocr url is empty ==");
            return Response.error("ocr url is empty");
        }

        String errorMsg = "Please take photos at a slightly longer distance for clear %s photo";
        String notRealPhotoMsg = "Please upload your real %s photo.";
        errorMsg = String.format(errorMsg, "pancard");
        notRealPhotoMsg = String.format(notRealPhotoMsg, "pancard");
        try {
            String front = downloadImg(Amazon2OssUtils.convertOssUrl(frontImgUrl));

            if (front == null) {
                LOGGER.error("== 进入advance ocr download front error ==");
                return Response.error("download error");
            }

            File frontFile = new File(front);
            if (!frontFile.exists()) {
                LOGGER.error("== 进入advance ocr file not exist local ==");
                return Response.error("file not exist local");
            }


            String frontOcrRes = ocrNew(frontFile, UserOcrTypeEnum.PAN_FRONT);
            LOGGER.info("== ocr返回内容 ==， frontOcrRes:{}", frontOcrRes);

            JSONObject jsonObject = JSON.parseObject(frontOcrRes);
            String code = jsonObject.getString("code");
            if (StringUtils.isNotEmpty(code) && !code.equalsIgnoreCase("SUCCESS")) {
                return Response.error(notRealPhotoMsg);
            }

            JSONObject dataObjectFront = jsonObject.getJSONObject("data");
            JSONObject resultObjectFront = dataObjectFront.getJSONObject("values");


            OcrCardInfoVO ocrCardInfoVo = new OcrCardInfoVO()
                    .setCard_no(resultObjectFront.getString("idNumber").replace(" ", ""))
                    .setDate_type("DOB")
                    .setName(resultObjectFront.getString("name"))
                    .setDate_info(resultObjectFront.getString("birthday"))
                    .setFather_name(resultObjectFront.getString("fatherName"));
            OcrCardResultVO ocrCardResultVoFront = new OcrCardResultVO()
                    .setCard_info(ocrCardInfoVo);

            OcrResponseVO ocrResponseVoFront = new OcrResponseVO()
                    .setRequest_id(jsonObject.getString("transactionId"))
                    .setStatus(jsonObject.getString("message"))
                    .setResults(Arrays.asList(ocrCardResultVoFront));

            return Response.ok().putData(ocrResponseVoFront);

        } catch (Exception e) {
            LOGGER.error("== 调用advance ai 异常2 ==", e);
        }

        return Response.error(errorMsg);
    }

    public String ocrNew(File frontFile, UserOcrTypeEnum ocrTypeEnum) {

        try {
            if (!frontFile.exists()) {
                LOGGER.error("== 进入advance ocr file not exist local ==");
                throw new ApplicationException("file not exist local");
            }


            List<Header> defaultHeaders = Arrays.asList(
                    new BasicHeader("X-ADVAI-KEY", apolloConfigUtil.getAadhaarAdvanceAiAccessKey())
            );

            CloseableHttpClient httpClient = HttpClients
                    .custom()
                    .setDefaultHeaders(defaultHeaders)
                    .build();


            HttpPost httpPost = new HttpPost(ADVANCE_OCR_URL_New);//建立HttpPost对象,改成自己的地址
            StringBody stringBody = new StringBody(ocrTypeEnum.name(), Charset.forName("UTF-8"));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
                    .create();
            multipartEntityBuilder.setCharset(Charset.forName("utf-8"))
                    .setContentType(ContentType.MULTIPART_FORM_DATA);
            FileBody fileBody = new FileBody(frontFile, ContentType.create("image/jpeg", Consts.UTF_8));
            multipartEntityBuilder.addPart("image", fileBody);//添加到请求

            HttpEntity entity = multipartEntityBuilder.addPart("cardType", stringBody)
                    .build();

            httpPost.setEntity(entity);
            HttpResponse response = null;//发送Post,并返回一个HttpResponse对象
            try {
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
                    String result = EntityUtils.toString(response.getEntity());
                    LOGGER.info("== ocr返回内容 ==，result:{}", result);
                    return result;
                }
            } catch (Exception e) {
                LOGGER.error("== 调用advance ai 异常1 ==", e);
            } finally {
                frontFile.delete();
            }

            throw new ApplicationException(" identity check failed ");
        } catch (Exception e) {
            LOGGER.error("== 调用advance ai 异常2 ==", e);
            throw new ApplicationException(" identity check failed ");
        }

    }


    public static String downloadImg(String fileUrl) {
        LOGGER.info("下载图片:" + fileUrl);
        //获取文件名，文件名实际上在URL中可以找到
        int index = fileUrl.lastIndexOf("?");
        String fileName = fileUrl.substring(index - 20, index) + System.currentTimeMillis() + ".jpg";
        //这里服务器上要将此图保存的路径
        String savePath = "/home/java/images/ocr";
        try {
            URL url = new URL(fileUrl);/*将网络资源地址传给,即赋值给url*/
            /*此为联系获得网络资源的固定格式用法，以便后面的in变量获得url截取网络资源的输入流*/
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = connection.getInputStream();

            DataInputStream in = new DataInputStream(connection.getInputStream());
            /*此处也可用BufferedInputStream与BufferedOutputStream*/
            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath + "/" + fileName));
            /*将参数savePath，即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
            byte[] buffer = new byte[4096];
            int count = 0;
            /*将输入流以字节的形式读取并写入buffer中*/
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();/*后面三行为关闭输入输出流以及网络资源的固定格式*/
            in.close();
            connection.disconnect();
            //返回内容是保存后的完整的URL
            LOGGER.info("下载完成:" + fileUrl + ",存储地址：" + savePath + "/" + fileName);
            return savePath + "/" + fileName;/*网络资源截取并存储本地成功返回true*/

        } catch (Exception e) {
            LOGGER.error("下载失败:" + fileUrl, e);
            return null;
        }
    }

    /**
     * 反欺诈
     *
     * @param data
     */
    @Override
    public Response<Double> antiHack(byte[] data) {
        HashMap<String, byte[]> hashMap = new HashMap<>(1);
        hashMap.put("liveness_data_file", data);
        String jsonStr = deepFinchHttpManager.doPost(ANTI_HACK_URL, null, hashMap);
        LOGGER.info("====反欺诈接口调用======response:{}", jsonStr);
        if (com.fqgj.common.utils.StringUtils.isEmpty(jsonStr)) {
            return Response.error("Internal Server Error");
        }
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String status = jsonObject.getString("status");
        if (Objects.equals(OK, status)) {
            LOGGER.info("====AccuauthOcr接口调用成功======response:{}", jsonStr);
            antiHackBuried(RequestLocalInfo.getCurrentUser() != null ? RequestLocalInfo.getCurrentUser().getUserCode() : "");
            double score = jsonObject.getDouble("score");
            return Response.ok().putData(score);
        } else {
            return Response.error(jsonObject.getString("reason"));
        }
    }


    public void antiHackBuried(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            return;
        }
        try {
            UserBehaviorEvent2Request userBehaviorEvent2Request = new UserBehaviorEvent2Request();
            userBehaviorEvent2Request.setUserCode(userCode);
            userBehaviorEvent2Request.setUserEventTrack(UserEventTrackEnum.third_party_anti_hack);
            userBehaviorService.addUserEventTrack(userBehaviorEvent2Request);
        } catch (Exception e) {
            LOGGER.error("反欺诈埋点失败,userCode:{}", userCode);
        }
    }

    public void advanceFaceBuried(String interfaceName, String userCode, String transactionId, Integer resultCode) {
        if (StringUtils.isEmpty(userCode)) {
            return;
        }
        try {
            ThirdCallHistoryRequest request = new ThirdCallHistoryRequest();
            request.setThirdTransactionId(transactionId);
            request.setUserCode(userCode);
            request.setServiceName("advance");
            request.setServiceCode("1");
            request.setInterfaceName(interfaceName);
            request.setResultCode(resultCode);
            userBehaviorService.addThirdCallHistory(request);
        } catch (Exception e) {
            LOGGER.error("advance反欺诈埋点失败,userCode:{}", userCode,e);
        }
    }

    private boolean isJson(String str) {
        try {
            JSONObject j = JSON.parseObject(str);
            return j.size() > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void checkAadhaar(AadhaarCardSaveDTO request) {
        JSONObject param = new JSONObject();
        param.put("aadhaarNo", request.getCardNo());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String response = HttpUtil.postPageBody(apolloConfigUtil.getRiskBaseUrl() + "/creditech/aadhaar/postRequest", headers, param.toJSONString());
        LOGGER.info("====aadhaar校验 request:{},response:{}", JSON.toJSONString(param), response);
        JSONObject jsonResponse = JSONObject.parseObject(response);
        if (jsonResponse == null || !Objects.equals(jsonResponse.getString("code"), "0")) {
            throw new ApplicationException("Verification failed，please check if the card number is correct");
        }
        //轮询结果
        int count = 3;
        String reportId = jsonResponse.getJSONObject("data").getString("reportId");

        JSONObject param1 = new JSONObject();
        param1.put("reportId", reportId);
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("Content-Type", "application/json");
        String result = "";
        for (int i = 0; i < count; i++) {
            String response1 = HttpUtil.postPageBody(apolloConfigUtil.getRiskBaseUrl() + "/creditech/aadhaar/getResult", headers1, param1.toJSONString());
            LOGGER.info("====aadhaar校验 获取结果 request:{},response:{}", JSON.toJSONString(param1), response1);
            JSONObject jsonResponse1 = JSONObject.parseObject(response1);
            if (jsonResponse1 != null && Objects.equals(jsonResponse1.getString("code"), "0")) {
                result = jsonResponse1.getJSONObject("data").getString("verifiedResult");
                break;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isEmpty(result) || result.contains("doesn't Exists!")) {
            throw new ApplicationException("Verification failed，please check if the card number is correct");
        }
    }

    @Override
    public AdvanceLivenessDetectionLicence advanceLivenessDetectionLicense(String userCode,String  packageName) {
      String key =  RedisKeyConsts.ADVANCE_LICENCE_KEY+packageName;
        if (redisClient.get(key) != null) {
            LOGGER.info("== 活体进入缓存 ===");
            AdvanceLivenessDetectionLicence advanceLivenessDetectionLicence = JSONObject.parseObject(redisClient.get(key), AdvanceLivenessDetectionLicence.class);
            return advanceLivenessDetectionLicence;
        }
        LOGGER.info("== 活体进入缓存  no===");
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("X-ADVAI-KEY", apolloConfigUtil.getAadhaarAdvanceAiAccessKey());
        JSONObject request = new JSONObject();
        request.put("licenseEffectiveSeconds", TimeConsts.ONE_DAY_AND_HALF);
//        String packageName = RequestLocalInfo.getRequestBasicInfo().getPackageName();
        if (!StringUtils.isEmpty(packageName)){
            request.put("applicationId",packageName);
        } else{
            request.put("applicationId","in.rupeemama.app" );
        }

        String responseStr = HttpUtil.postPageBodyByHttps(ADVANCE_LIVENESS_DETECTION_LICENSE, header, request.toJSONString());
        LOGGER.info("调用Advance LivenessDetection 校验接口,header:{},request:{},response:{}", JSON.toJSONString(header), request.toJSONString(), responseStr);
        JSONObject response = JSON.parseObject(responseStr);
        String code = response.getString("code");
        String message = response.getString("message");
        String transactionId = response.getString("transactionId");
        String pricingStrategy = response.getString("pricingStrategy");
        advanceFaceBuried("advance_livenes_license", userCode, transactionId, "PAY".equalsIgnoreCase(pricingStrategy) ? 1 : 0);
        if (!"SUCCESS".equals(code)) {
            throw new ApplicationException("Failed: " + message);
        }
        String data = response.getString("data");
        AdvanceLivenessDetectionLicence advanceLivenessDetectionLicence = JSONObject.parseObject(data, AdvanceLivenessDetectionLicence.class);
        long expireSecond = (advanceLivenessDetectionLicence.getExpireTimestamp() - System.currentTimeMillis()) / 1000 - 1000;
        redisClient.set(key, JSONObject.toJSONString(advanceLivenessDetectionLicence), expireSecond);
        return advanceLivenessDetectionLicence;
    }

    @Override
    public AdvanceLivenessDetection advanceLivenessDetection(String userCode, String livenessId) {
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("X-ADVAI-KEY", apolloConfigUtil.getAadhaarAdvanceAiAccessKey());

        JSONObject request = new JSONObject();
        request.put("livenessId", livenessId);
        request.put("resultType", "IMAGE_BASE64");
        String responseStr = HttpUtil.postPageBodyByHttps(ADVANCE_LIVENESS_DETECTION, header, request.toJSONString());
        JSONObject response = JSON.parseObject(responseStr);
        String code = response.getString("code");
        String message = response.getString("message");
        String transactionId = response.getString("transactionId");
        String pricingStrategy = response.getString("pricingStrategy");
        advanceFaceBuried("advance_livenes_detection", userCode, transactionId, "PAY".equalsIgnoreCase(pricingStrategy) ? 1 : 0);
        if (!"SUCCESS".equals(code)) {
            throw new ApplicationException("Failed: " + message);
        }
        String data = response.getString("data");
        AdvanceLivenessDetection advanceLivenessDetection = JSONObject.parseObject(data, AdvanceLivenessDetection.class);
        if (StringUtils.isNotEmpty(advanceLivenessDetection.getDetectionResult())) {
            String date = DateUtil.getDate(new Date());
            InputStream inputStream = Base64ConvertUtil.base64ToPdf(advanceLivenessDetection.getDetectionResult());
            String fileStr = Joiner.on("_").join(userCode, date, System.currentTimeMillis(), "advance_liveness.png");
            String awsFilePath = "advance/" + date + "/" + fileStr;
            String fileUrl = "";
            try {
                ossService.uploadFile(apolloConfigUtil.getBucketName(), inputStream, inputStream.available(), awsFilePath);
                fileUrl = apolloConfigUtil.getOssBaseUrl() + awsFilePath;
                LOGGER.info("==== advance人脸识别上传图片成功,transactionId:{}, fileUrl:{} =====", transactionId, fileUrl);
            } catch (Exception e) {
                LOGGER.error("上传图片失败,transactionId:{},photoBase64:{}", transactionId, advanceLivenessDetection.getDetectionResult(), e);
            } finally {
                try {
                    inputStream.close();
                } catch (Exception ex) {
                }
            }
            advanceLivenessDetection.setDetectionResult(fileUrl);
        }
        return advanceLivenessDetection;
    }


}
